﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AutoItX3Lib;
using System.Runtime.InteropServices;
using System.IO;
using CommonFunction;
using System.Runtime.Remoting.Messaging;
using System.Threading;
using System.Diagnostics;
using OneNote = Microsoft.Office.Interop.OneNote;
using System.Drawing.Imaging;
using System.Xml;

namespace PokeristBOT
{
    public partial class BOTMain : Form
    {
        private const string TITLE_PATTERN = "Pokerist Pro -::- {0}";
        private const int IMG_WIDTH = 15, IMG_HEIGH = 15;
        private const string IMG_INVITE_OK_NAME = "Invitation.jpg";
        private const string IMG_BUY_GAME_NAME = "BuyingGame.jpg";
        private const string IMG_FIRST_TURN_NAME = "FirstTurn.jpg";
        private const string IMG_SECOND_TURN_NAME = "SecondTurn.jpg";
        private const string IMG_THIRD_TURN_NAME = "ThirdTurn.jpg";
        private const string IMG_FOURTH_TURN_NAME = "FourthTurn.jpg";
        private const string IMG_READY_NAME = "Ready.jpg";
        private const string IMG_CHECK_NAME = "Check.jpg";
        private const string IMG_HIGH_CARD_NAME = "HighCard.jpg";
        private const string IMG_PAIR_NAME = "Pair.jpg";
        private const string IMG_2PAIR_NAME = "TwoPair.jpg";
        private const string IMG_THREE_OF_KIND_NAME = "ThreeOfKind.jpg";
        private const string IMG_STRAIGHT_NAME = "Straight.jpg";
        private const string IMG_FLUSH_NAME = "Flush.jpg";
        private const string IMG_FULL_HOUSE_NAME = "FullHouse.jpg";
        private const string IMG_4OF_KIND_NAME = "FourOfKind.jpg";
        private const string IMG_STRAIGHT_FLUSH_NAME = "StraightFlush.jpg";
        private const string IMG_NOTOPEN_NAME = "NotOpen.jpg";
        private const string IMG_OPEN3_NAME = "Open3.jpg";
        private const string IMG_OPEN4_NAME = "Open4.jpg";
        
        //OneNote namespace
        static String strNamespace = "http://schemas.microsoft.com/office/onenote/2010/onenote";

        private static AutoItX3 autoit;

        private delegate void delPlaying();
        
        private string IMAGE_PATH = "";
        private string IMAGE_TEMP_NAME1 = "picTemp.jpg";
        private int MIN_PAIR = 9, HIGH_CARD = 0, CURR_CARD = 2;
        private string WINDOW_TITLE = "";
        private IntPtr HANDLER;
        private int TABLE_TYPE = 9;
        private LOCATION GAME_LOCATION = LOCATION.LOBBY;
        private int BUY_GAME_POS_X_MIN = 309, BUY_GAME_POS_X_MAX = 465, RAISE_POS_X_MIN = 300, RAISE_POS_X_MAX = 458;        
        private int MONEY_AMOUNT = 5, FIRST_RAISE = 5, SECOND_RAISE = 3, THIRD_RAISE = 4, FOURTH_RAISE = 10, CURRENT_RAISE = 1;
        private int RESET_FOLD = 9, GAME_DELAY = 1000, EMTY_SEAT_LEAVE = 0, EMTY_SEAT_DELAY = 300000, FOLLOW_AMOUNT = 0, AUTO_SEAT = 0;
        private int FOLD_COUNT = 0;
        private bool GAME_BUSY = true;
        private MAIN_STATE GAME_STATUS = MAIN_STATE.STOP;
        private SUB_STATE_PLAYING PLAYING_STATUS = SUB_STATE_PLAYING.PLAY_READY;
        private SUB_STATE_WAITING_INVITATION WAIT_INVITE_STATUS = SUB_STATE_WAITING_INVITATION.WAIT_DIALOG;

        enum LOCATION
        {
            LOBBY = 0,
            PLAYING = 1,
            SITTING = 2
        }

        enum MAIN_STATE
        {
            STOP = 0,
            WAIT_INVITATION = 1,
            SEARCHING_SEAT = 2,
            PLAYING = 3
        }

        enum SUB_STATE_WAITING_INVITATION
        {
            WAIT_DIALOG = 0,
            WAIT_BUY_GAME = 1
        }

        enum SUB_STATE_PLAYING
        {
            PLAY_READY = 0,
            CHECK_TURN_THIRD_FOURTH = 1,
            CHECK_TURN_SECOND = 2,
            MONEY_QUALIFY = 3,
            CARD_QUALIFY = 4,
            DO_ACTION = 5,
            RESET_AMOUNT = 6
        }

        public BOTMain()
        {
            InitializeComponent();
            InitConfiguration();
        }

        private void BOTMain_Load(object sender, EventArgs e)
        {

        }

        private void InitConfiguration()
        {
            this.cboMinCard.SelectedIndex = 7;
            this.cboLocation.SelectedIndex = 0;
            this.cboHighCard.SelectedIndex = 0;
            this.cboTable.SelectedIndex = 0;

            this.HANDLER = this.browserGame.Handle;
            this.IMAGE_PATH = Path.Combine(Application.StartupPath, "Images");

            autoit = new AutoItX3();
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            if (ChangeTitleValidation())
            {
                ChangeTitle(txtTitle.Text);
                ChangeTitleBehaviour(true);
            }
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            ChangeTitleBehaviour(false);
        }

        private void btnPlayStop_Click(object sender, EventArgs e)
        {
            if (btnPlayStop.Text == "Play")
            {
                ChangeTitle("Stop", btnPlayStop);
                PlayBehaviour(true);
            }
            else
            {
                ChangeTitle("Play", btnPlayStop);
                PlayBehaviour(false);
            }
        }

        private void slide_Scroll(object sender, EventArgs e)
        {
            TrackBar slider = (TrackBar)sender;
            ChangeTitle(string.Format("{0}%", slider.Value), panelConfigParam.Controls[slider.Tag.ToString()]);
            slider = null;
        }

        private void btnSignOut_Click(object sender, EventArgs e)
        {
            var confirm = MessageBox.Show("Do you want to sign out the poker?", "Sign out Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (confirm == System.Windows.Forms.DialogResult.Yes)
            {
                this.browserGame.Url = new Uri("http://app.pokerist.com/assets/poker-client/poker-1395732447.swf");
            }
        }

        private void timerEmtySeat_Tick(object sender, EventArgs e)
        {

        }

        private void timerAutoSeat_Tick(object sender, EventArgs e)
        {

        }

        private void BOTMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F3)
            {
                this.Width = this.panelLeft.Width + 20;
            }
            else if (e.KeyCode == Keys.F4)
            {
                this.Width = 1020;
            }
        }

        private void browserGame_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            BOTMain_KeyDown(this, new KeyEventArgs(e.KeyCode));
        }

        private void browserGame_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            SetEnableControl(grpTitle, true);
        }

        private void BOTMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            autoit = null;
            GC.Collect();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var image = CaptureImage(this.browserGame.Handle, Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text),
                Convert.ToInt32(textBox3.Text), Convert.ToInt32(textBox4.Text));

            string path = Path.Combine(Application.StartupPath, @"temp.jpg");

            image.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);

            image.Dispose();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            autoit.ControlClick(this.Text, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 1, Convert.ToInt32(textBox5.Text), Convert.ToInt32(textBox6.Text));
            //MessageBox.Show(CurrentCallAmount().ToString());
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Image imgTemp1 = Image.FromFile(Path.Combine(Application.StartupPath, textBox7.Text.Trim() + ".jpg"));
            Image imgTemp2 = Image.FromFile(Path.Combine(Application.StartupPath, textBox8.Text.Trim() + ".jpg"));
            MessageBox.Show(imgTemp1.EqualTo(imgTemp2).ToString());
        }

        #region "validation methods"

        private bool ChangeTitleValidation()
        {
            if (string.IsNullOrEmpty(txtTitle.Text))
            {
                MessageBox.Show("Please enter the title of the Poker !", string.Format(TITLE_PATTERN, "Validation"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtTitle.Focus();
                return false;
            }

            AutoItX3 autoit = new AutoItX3();
            var winExist = autoit.WinExists(string.Format(TITLE_PATTERN, txtTitle.Text));
            autoit = null;
            if (winExist == 1)
            {
                MessageBox.Show("The poker's title is existed. Please enter another title of the Poker !", string.Format(TITLE_PATTERN, "Validation"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtTitle.SelectAll();
                txtTitle.Focus();
                return false;
            }

            return true;
        }

        #endregion

        #region "behaviour methods"

        private void ChangeTitleBehaviour(bool isApplied)
        {
            SetEnableControl(btnModify, isApplied);
            SetEnableControl(btnApply, !isApplied);
            SetEnableControl(grpConfiguration, isApplied);
            SetEnableControl(txtTitle, !isApplied);
        }

        private void PlayBehaviour(bool isPlay)
        {
            SetEnableControl(btnSignOut, !isPlay);
            SetEnableControl(panelConfigParam, !isPlay);

            if (isPlay)
            {
                PlayGameInitialization();                
                delPlaying play = new delPlaying(PlayGame);
                play.BeginInvoke(new AsyncCallback(CallbackMethod), null);
            }
            else
            {
                StopGameInitialization();
            }
        }

        private void PlayGameInitialization()
        {
            GAME_BUSY = false;

            MIN_PAIR = cboMinCard.SelectedIndex + 2;
            HIGH_CARD = cboHighCard.SelectedIndex + 9;
            TABLE_TYPE = cboTable.SelectedIndex == 0 ? 9 : 5;
            GAME_LOCATION = cboLocation.SelectedIndex == 0 ? LOCATION.LOBBY : cboLocation.SelectedIndex == 1 ? LOCATION.PLAYING : LOCATION.SITTING;
            MONEY_AMOUNT = Convert.ToInt32(slideAmount.Value);
            FIRST_RAISE = Convert.ToInt32(slideFirst.Value);
            SECOND_RAISE = Convert.ToInt32(slideSecond.Value);
            THIRD_RAISE = Convert.ToInt32(slideThird.Value);
            FOURTH_RAISE = Convert.ToInt32(slideFourth.Value);
            RESET_FOLD = Convert.ToInt32(updResetFold.Value);
            GAME_DELAY = Convert.ToInt32(updGameDelay.Value) * 1000;
            EMTY_SEAT_LEAVE = Convert.ToInt32(updEmptySeat.Value);
            EMTY_SEAT_DELAY = Convert.ToInt32(updEmptySeatDelay.Value) * 1000;
            FOLLOW_AMOUNT = Convert.ToInt32(updFollow.Value);
            AUTO_SEAT = Convert.ToInt32(updAutoSeat.Value) * 1000;

            //if (EMTY_SEAT_LEAVE > 0 && EMTY_SEAT_DELAY > 0)
            //{
            //    this.timerEmtySeat.Enabled = true;
            //    this.timerEmtySeat.Interval = EMTY_SEAT_DELAY;
            //    this.timerEmtySeat.Start();
            //}

            //if (AUTO_SEAT > 0)
            //{
            //    this.timerAutoSeat.Enabled = true;
            //    this.timerAutoSeat.Interval = AUTO_SEAT;
            //    this.timerAutoSeat.Start();
            //}

            if (GAME_LOCATION == LOCATION.LOBBY)
            {
                GAME_STATUS = MAIN_STATE.WAIT_INVITATION;
                WAIT_INVITE_STATUS = SUB_STATE_WAITING_INVITATION.WAIT_DIALOG;
            }
            else if (GAME_LOCATION == LOCATION.SITTING)
            {
                GAME_STATUS = MAIN_STATE.SEARCHING_SEAT;
            }
            else
            {
                GAME_STATUS = MAIN_STATE.PLAYING;
                PLAYING_STATUS = SUB_STATE_PLAYING.PLAY_READY;
            }
        }

        private void StopGameInitialization()
        {
            GAME_BUSY = true;

            GAME_STATUS = MAIN_STATE.STOP;

            //TODO: reset the sub state of each main state

            this.timerEmtySeat.Stop();
            this.timerEmtySeat.Enabled = false;

            this.timerAutoSeat.Stop();
            this.timerAutoSeat.Enabled = false;
        }

        private void PlayGame()
        {            
            if (GAME_BUSY) return;

            switch (GAME_STATUS)
            {
                case MAIN_STATE.STOP:
                    break;

                case MAIN_STATE.WAIT_INVITATION:
                    WaitingInvitation();
                    break;

                case MAIN_STATE.SEARCHING_SEAT:
                    break;

                case MAIN_STATE.PLAYING:
                    PlayingTemp();
                    //Playing();
                    break;

                default: break;
            }

            GC.Collect();
        }

        private void WaitingInvitation()
        {
            switch (WAIT_INVITE_STATUS)
            {
                case SUB_STATE_WAITING_INVITATION.WAIT_DIALOG:
                    if (IsInvited())
                    {
                        autoit.ControlClick(WINDOW_TITLE, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 5, 443, 410);
                        WAIT_INVITE_STATUS = SUB_STATE_WAITING_INVITATION.WAIT_BUY_GAME;
                    }
                    break;

                case SUB_STATE_WAITING_INVITATION.WAIT_BUY_GAME:
                    if (IsBuyingGame())
                    {
                        BuyGame();

                        WAIT_INVITE_STATUS = SUB_STATE_WAITING_INVITATION.WAIT_DIALOG;
                        GAME_STATUS = MAIN_STATE.PLAYING;
                    }
                    break;

                default:
                    //this.timerGame.Stop();
                    //this.timerGame.Interval = GAME_DELAY;
                    //this.timerGame.Start();
                    break;
            }
        }
        
        private void PlayingTemp()
        {
            if (IsReady)
            {
                //TODO: capture cards for directory
                //CaptureCard();
                //Fold();
                //return;

                if (CanRaise)
                {
                    CurrentTurn();
                    Raise();
                    ReLoadAmount();
                }
                //else if (IsCheckEnabled)
                //{
                //    Check();
                //}
                //else if (CanFollow)
                //{
                //    Follow();
                //}
                else
                {
                    Fold();

                    FOLD_COUNT++;
                    if (FOLD_COUNT >= RESET_FOLD)
                    {
                        ReLoadAmount();
                        FOLD_COUNT = 0;
                    }
                }
            }

            GC.Collect();

            return;
        }

        /*
        private void Playing()
        {
            switch (PLAYING_STATUS)
            {
                case SUB_STATE_PLAYING.PLAY_READY:
                    if (IsReady)
                    {
                        PLAYING_STATUS = SUB_STATE_PLAYING.CHECK_TURN_THIRD_FOURTH;

                    }
                    break;

                case SUB_STATE_PLAYING.CHECK_TURN_THIRD_FOURTH:
                    //if (IsFourthTurn())
                    //{
                    //    CURRENT_RAISE = FOURTH_RAISE;
                    //    Raise();
                    //    PLAYING_STATUS = SUB_STATE_PLAYING.RESET_AMOUNT;
                    //}
                    //else if (IsThirdTurn())
                    //{
                    //    CURRENT_RAISE = THIRD_RAISE;
                    //    Raise();
                    //}
                    //else
                    //{
                    //    PLAYING_STATUS = SUB_STATE_PLAYING.CHECK_TURN_SECOND;
                    //}
                    break;

                case SUB_STATE_PLAYING.CHECK_TURN_SECOND:
                    //if(IsSecondTurn())
                    //{
                    //    if (FOLLOW_AMOUNT == 0)
                    //    {
                    //        Raise();
                    //        PLAYING_STATUS = SUB_STATE_PLAYING.RESET_AMOUNT;
                    //    }
                    //    else
                    //    {
                    //        PLAYING_STATUS = SUB_STATE_PLAYING.CARD_QUALIFY;
                    //    }
                    //}
                    //else if (FOLLOW_AMOUNT == 0)
                    //{
                    //    PLAYING_STATUS = SUB_STATE_PLAYING.CARD_QUALIFY;
                    //}
                    //else
                    //{
                    //    PLAYING_STATUS = SUB_STATE_PLAYING.MONEY_QUALIFY;
                    //}                    
                    break;

                case SUB_STATE_PLAYING.MONEY_QUALIFY:
                    if (IsMoneyQualify())
                    {
                        Raise();
                        PLAYING_STATUS = SUB_STATE_PLAYING.RESET_AMOUNT;
                    }
                    else
                    {
                        Fold();

                        FOLD_COUNT++;
                        if (FOLD_COUNT >= RESET_FOLD)
                        {
                            FOLD_COUNT = 0;
                            PLAYING_STATUS = SUB_STATE_PLAYING.RESET_AMOUNT;
                        }
                        else
                        {
                            PLAYING_STATUS = SUB_STATE_PLAYING.PLAY_READY;

                            break;
                        }
                    }
                    break;

                case SUB_STATE_PLAYING.CARD_QUALIFY:

                    if (IsStraightFlush() || IsFourOfKind() || IsFullHouse() || IsFlush() || IsStraight() || IsThreeOfKind() || IsTwoPair())
                    {
                        Raise();
                        PLAYING_STATUS = SUB_STATE_PLAYING.RESET_AMOUNT;
                    }
                    else if (MIN_PAIR >= 19)    //any
                    {
                        Raise();
                        PLAYING_STATUS = SUB_STATE_PLAYING.RESET_AMOUNT;
                    }
                    else if (MIN_PAIR <= 15)    //pair
                    {
                        if (IsPair() && CurrentCard() >= MIN_PAIR)
                        {
                            Raise();
                            PLAYING_STATUS = SUB_STATE_PLAYING.RESET_AMOUNT;
                        }
                        else
                        {
                            Fold();

                            FOLD_COUNT++;
                            if (FOLD_COUNT >= RESET_FOLD)
                            {
                                FOLD_COUNT = 0;
                                PLAYING_STATUS = SUB_STATE_PLAYING.RESET_AMOUNT;
                            }
                            else
                            {
                                PLAYING_STATUS = SUB_STATE_PLAYING.PLAY_READY;

                                break;
                            }
                        }
                    }
                    else
                    {
                        if (!IsHighCard())
                        {
                            Raise();
                            PLAYING_STATUS = SUB_STATE_PLAYING.RESET_AMOUNT;
                        }
                        else if (IsHighCard_A())
                        {
                            if (MIN_PAIR == 18 || (MIN_PAIR == 16 && IsHighCard_KQ(true)) || (MIN_PAIR == 17 && IsHighCard_KQ(false)))
                            {
                                Raise();
                                PLAYING_STATUS = SUB_STATE_PLAYING.RESET_AMOUNT;
                            }
                            else
                            {
                                Fold();

                                FOLD_COUNT++;
                                if (FOLD_COUNT >= RESET_FOLD)
                                {
                                    FOLD_COUNT = 0;
                                    PLAYING_STATUS = SUB_STATE_PLAYING.RESET_AMOUNT;
                                }
                                else
                                {
                                    PLAYING_STATUS = SUB_STATE_PLAYING.PLAY_READY;

                                    break;
                                }
                            }
                        }
                        else
                        {
                            Fold();

                            FOLD_COUNT++;
                            if (FOLD_COUNT >= RESET_FOLD)
                            {
                                FOLD_COUNT = 0;
                                PLAYING_STATUS = SUB_STATE_PLAYING.RESET_AMOUNT;
                            }
                            else
                            {
                                PLAYING_STATUS = SUB_STATE_PLAYING.PLAY_READY;

                                break;
                            }
                        }
                    }

                    break;

                case SUB_STATE_PLAYING.DO_ACTION:
                    break;

                case SUB_STATE_PLAYING.RESET_AMOUNT:
                    PLAYING_STATUS = SUB_STATE_PLAYING.PLAY_READY;
                    break;

                default:
                    PLAYING_STATUS = SUB_STATE_PLAYING.PLAY_READY;

                    break;
            }
        }
        */

        #endregion

        #region "invoke methods"

        private void SetEnableControl(Control ctrl, bool state)
        {
            if (ctrl.InvokeRequired)
                SetEnableControl(ctrl, state);
            else
                ctrl.Enabled = state;
        }

        private void ChangeTitle(string title)
        {
            if (this.InvokeRequired)
                ChangeTitle(title);
            else
            {
                this.Text = string.Format(TITLE_PATTERN, title);
                WINDOW_TITLE = string.Format(TITLE_PATTERN, title);
            }
        }

        private void ChangeTitle(string title, Control ctrl)
        {
            if (ctrl.InvokeRequired)
                ChangeTitle(title, ctrl);
            else
                ctrl.Text = title;
        }

        private void CallbackMethod(IAsyncResult result)
        {
            try
            {
                if (result.IsCompleted)
                {
                    delPlaying worker = (delPlaying)((AsyncResult)result).AsyncDelegate;
                    worker.EndInvoke(result);

                    if (GAME_DELAY > 0) Thread.Sleep(GAME_DELAY);

                    if (!GAME_BUSY)
                    {
                        delPlaying play = new delPlaying(PlayGame);
                        play.BeginInvoke(new AsyncCallback(CallbackMethod), null);
                    }
                }
            }
            catch
            {
                if (!GAME_BUSY)
                {
                    delPlaying play = new delPlaying(PlayGame);
                    play.BeginInvoke(new AsyncCallback(CallbackMethod), null);
                }
            }
        }

        #endregion

        #region "process methods"

        private bool IsInvited()
        {
            return IsMatch(IMG_INVITE_OK_NAME, IMAGE_TEMP_NAME1, 435, 400);
        }

        private bool IsBuyingGame()
        {
            return IsMatch(IMG_BUY_GAME_NAME, IMAGE_TEMP_NAME1, 310, 115);
        }

        private bool IsReady
        {
            get
            {
                return IsMatch(IMG_READY_NAME, "IsReady.jpg", 277, 565);
            }
        }

        private bool IsCheckEnabled
        {
            get
            {
                return IsMatch(IMG_CHECK_NAME, "isCheckEnabled.jpg", 277, 532);
            }
        }

        private bool CanFollow
        {
            get
            {
                try
                {
                    if (FOLLOW_AMOUNT <= 0 || HIGH_CARD <= 9) return false;

                    Image imgTurn = null;
                    Image imgTemp = null;

                    //not open card
                    if (File.Exists(Path.Combine(IMAGE_PATH, IMG_NOTOPEN_NAME)))
                    {
                        imgTurn = Image.FromFile(Path.Combine(IMAGE_PATH, IMG_NOTOPEN_NAME));
                        imgTemp = CaptureImage(this.HANDLER, 290, 250, 10, 10);
                        imgTemp.Save(Path.Combine(IMAGE_PATH, "IsNotOpen.jpg"));
                        imgTemp.Dispose();
                        imgTemp = null;
                        imgTemp = Image.FromFile(Path.Combine(IMAGE_PATH, "IsNotOpen.jpg"));

                        var isMatch = imgTurn.EqualTo(imgTemp);

                        imgTurn.Dispose();
                        imgTurn = null;
                        imgTemp.Dispose();
                        imgTemp = null;

                        if (!isMatch) return false;
                    }

                    if (!IsHighCard_KQJ()) return false;

                    var currCallAmt = CurrentCallAmount();
                    
                    if (FOLLOW_AMOUNT < currCallAmt) return false;
                    if (HIGH_CARD == 10 && IsPair()) return true;
                    
                    return true;
                }
                catch { }

                return false;
            }
        }

        private bool IsHighCard()
        {
            return IsMatch(IMG_HIGH_CARD_NAME, "isHighCard.jpg", 690, 660, 10, 10);
        }

        private bool IsPair()
        {
            return IsMatch(IMG_PAIR_NAME, "isPair.jpg", 620, 660, 10, 10);
        }

        private bool IsTwoPair()
        {
            return IsMatch(IMG_2PAIR_NAME, "isTwoPair.jpg", 520, 660, 10, 10);
        }

        private bool IsThreeOfKind()
        {
            return IsMatch(IMG_THREE_OF_KIND_NAME, "isThreeOfKind.jpg", 425, 660, 10, 10);
        }

        private bool IsStraight()
        {
            return IsMatch(IMG_STRAIGHT_NAME, "isStraight.jpg", 355, 660, 10, 10);
        }

        private bool IsFlush()
        {
            return IsMatch(IMG_FLUSH_NAME, "isFlush.jpg", 283, 660, 10, 10);
        }

        private bool IsFullHouse()
        {
            return IsMatch(IMG_FULL_HOUSE_NAME, "isFullHouse.jpg", 185, 660, 10, 10);
        }

        private bool IsFourOfKind()
        {
            return IsMatch(IMG_4OF_KIND_NAME, "isFourOfKind.jpg", 95, 660, 10, 10);
        }

        private bool IsStraightFlush()
        {
            return IsMatch(IMG_STRAIGHT_FLUSH_NAME, "isStraightFlush.jpg", 5, 660, 10, 10);
        }

        private bool IsMoneyQualify()
        {
            var imgTemp = CaptureImage(this.HANDLER, 417, 406, 15, 15);
            imgTemp.Save(Path.Combine(IMAGE_PATH, IMAGE_TEMP_NAME1));
            imgTemp.Dispose();
            imgTemp = null;
            imgTemp = Image.FromFile(Path.Combine(IMAGE_PATH, IMAGE_TEMP_NAME1));

            string moneyFileName = "";
            for (int i = 1; i < 30; i++)
            {
                moneyFileName = Path.Combine(IMAGE_PATH, string.Format("M_{0}.jpg", i));
                if (File.Exists(moneyFileName))
                {
                    if (IsMatch(imgTemp, moneyFileName))
                    {
                        imgTemp.Dispose();
                        imgTemp = null;

                        if (FOLLOW_AMOUNT >= i) return true;
                        break;
                    }
                }
            }

            return false;
        }

        private bool CanRaise
        {
            get
            {
                try
                {
                    if (IsStraightFlush()) return true;
                    if (IsFourOfKind()) return true;
                    if (IsFullHouse()) return true;
                    if (IsFlush()) return true;
                    if (IsStraight()) return true;
                    if (IsThreeOfKind()) return true;
                    if (IsTwoPair()) return true;

                    CURR_CARD = CurrentCard();

                    if (IsPair() && CURR_CARD >= MIN_PAIR) return true;

                    return false;
                }
                catch { return false; }
            }
        }

        private bool PairMeet()
        {
            return false;
        }

        private void Raise()
        {
            var raisePosX = Convert.ToInt32(RAISE_POS_X_MIN + Math.Floor((RAISE_POS_X_MAX - RAISE_POS_X_MIN) * CURRENT_RAISE / 100.00));

            //increase amount to raise
            autoit.ControlClick(this.Text, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 10, raisePosX, 606);

            //click on raise button
            autoit.ControlClick(this.Text, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 1, 430, 573);

            //click on call any button
            autoit.ControlClick(this.Text, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 1, 430, 541);
        }

        private void Fold()
        {
            //click on fold button
            autoit.ControlClick(this.Text, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 1, 323, 573);

            //click ok if reload money at the middle game
            autoit.ControlClick(WINDOW_TITLE, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 4, 382, 408);

            //click close button to close the profile
            autoit.ControlClick(WINDOW_TITLE, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 1, 732, 510);

            FOLD_COUNT++;
            if (FOLD_COUNT >= RESET_FOLD)
            {
                FOLD_COUNT = 0;
                ReLoadAmount();
            }
        }

        private void Check()
        {
            //check button
            autoit.ControlClick(this.Text, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 1, 323, 541);
        }

        private void Follow()
        {
            //call button
            autoit.ControlClick(this.Text, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 1, 430, 541);
        }

        private void ReLoadAmount()
        {
            //click on the profile
            autoit.ControlClick(this.Text, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 1, 381, 427);

            //click on the reload amount icon
            autoit.ControlClick(this.Text, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 1, 638, 657);

            //click on buy game window
            BuyGame();
        }

        private void BuyGame()
        {
            var buyGamePosX = Convert.ToInt32(BUY_GAME_POS_X_MIN + Math.Floor((BUY_GAME_POS_X_MAX - BUY_GAME_POS_X_MIN) * MONEY_AMOUNT / 100.00));

            if (MONEY_AMOUNT == 100) buyGamePosX = 482;

            //reset amount to zero to buy game
            //autoit.ControlClick(WINDOW_TITLE, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 10, 292, 236);

            //turning on amount to buy game
            autoit.ControlClick(WINDOW_TITLE, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 10, buyGamePosX, 235);

            //click OK to buy game
            autoit.ControlClick(WINDOW_TITLE, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 1, 461, 401);

            //click ok if reload money at the middle game
            autoit.ControlClick(WINDOW_TITLE, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 4, 382, 408);

            //click close button to close the profile
            autoit.ControlClick(WINDOW_TITLE, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 1, 732, 510);
        }

        private int CurrentCard()
        {
            var imgTemp = CaptureImage(this.HANDLER, 418, 407, 9, 13);
            imgTemp.Save(Path.Combine(IMAGE_PATH, "currCard.jpg"));
            imgTemp.Dispose();
            imgTemp = null;
            imgTemp = Image.FromFile(Path.Combine(IMAGE_PATH, "currCard.jpg"));

            string cardFileName = "";
            for (int i = 2; i < 15; i++)
            {
                cardFileName = Path.Combine(IMAGE_PATH, string.Format("R_{0}.jpg", i));
                if (File.Exists(cardFileName))
                {
                    if (IsMatch(imgTemp, cardFileName))
                    {
                        imgTemp.Dispose();
                        imgTemp = null;
                        return i;
                    }
                }

                cardFileName = Path.Combine(IMAGE_PATH, string.Format("B_{0}.jpg", i));
                if (!File.Exists(cardFileName)) continue;
                if (IsMatch(imgTemp, cardFileName))
                {
                    imgTemp.Dispose();
                    imgTemp = null;
                    return i;
                }
            }

            cardFileName = Path.Combine(IMAGE_PATH, "R_14_2.jpg");
            if (File.Exists(cardFileName))
            {
                if (IsMatch(imgTemp, cardFileName))
                {
                    imgTemp.Dispose();
                    imgTemp = null;
                    return 14;
                }
            }
            cardFileName = Path.Combine(IMAGE_PATH, "B_14_2.jpg");
            if (File.Exists(cardFileName))
            {
                if (IsMatch(imgTemp, cardFileName))
                {
                    imgTemp.Dispose();
                    imgTemp = null;
                    return 14;
                }
            }

            cardFileName = Path.Combine(IMAGE_PATH, "R_13_2.jpg");
            if (File.Exists(cardFileName))
            {
                if (IsMatch(imgTemp, cardFileName))
                {
                    imgTemp.Dispose();
                    imgTemp = null;
                    return 13;
                }
            }
            cardFileName = Path.Combine(IMAGE_PATH, "B_13_2.jpg");
            if (File.Exists(cardFileName))
            {
                if (IsMatch(imgTemp, cardFileName))
                {
                    imgTemp.Dispose();
                    imgTemp = null;
                    return 13;
                }
            }

            cardFileName = Path.Combine(IMAGE_PATH, "R_12_2.jpg");
            if (File.Exists(cardFileName))
            {
                if (IsMatch(imgTemp, cardFileName))
                {
                    imgTemp.Dispose();
                    imgTemp = null;
                    return 12;
                }
            }
            cardFileName = Path.Combine(IMAGE_PATH, "B_12_2.jpg");
            if (File.Exists(cardFileName))
            {
                if (IsMatch(imgTemp, cardFileName))
                {
                    imgTemp.Dispose();
                    imgTemp = null;
                    return 12;
                }
            }

            cardFileName = Path.Combine(IMAGE_PATH, "R_11_2.jpg");
            if (File.Exists(cardFileName))
            {
                if (IsMatch(imgTemp, cardFileName))
                {
                    imgTemp.Dispose();
                    imgTemp = null;
                    return 11;
                }
            }
            cardFileName = Path.Combine(IMAGE_PATH, "B_11_2.jpg");
            if (File.Exists(cardFileName))
            {
                if (IsMatch(imgTemp, cardFileName))
                {
                    imgTemp.Dispose();
                    imgTemp = null;
                    return 11;
                }
            }

            return -1;
        }

        private void CurrentTurn()
        {
            try
            {
                Image imgTurn = null;
                Image imgTemp = null;

                //not open card
                if (File.Exists(Path.Combine(IMAGE_PATH, IMG_NOTOPEN_NAME)))
                {
                    imgTurn = Image.FromFile(Path.Combine(IMAGE_PATH, IMG_NOTOPEN_NAME));
                    imgTemp = CaptureImage(this.HANDLER, 290, 250, 10, 10);
                    imgTemp.Save(Path.Combine(IMAGE_PATH, "IsNotOpen.jpg"));
                    imgTemp.Dispose();
                    imgTemp = null;
                    imgTemp = Image.FromFile(Path.Combine(IMAGE_PATH, "IsNotOpen.jpg"));

                    var isMatch = imgTurn.EqualTo(imgTemp);

                    imgTurn.Dispose();
                    imgTurn = null;
                    imgTemp.Dispose();
                    imgTemp = null;
                    if (isMatch)
                    {
                        CURRENT_RAISE = FIRST_RAISE;
                        return;
                    }
                }

                //open 3 card                        
                if (File.Exists(Path.Combine(IMAGE_PATH, IMG_OPEN3_NAME)))
                {
                    imgTurn = Image.FromFile(Path.Combine(IMAGE_PATH, IMG_OPEN3_NAME));
                    imgTemp = CaptureImage(this.HANDLER, 420, 250, 10, 10);
                    imgTemp.Save(Path.Combine(IMAGE_PATH, "IsOpen3.jpg"));
                    imgTemp.Dispose();
                    imgTemp = null;
                    imgTemp = Image.FromFile(Path.Combine(IMAGE_PATH, "IsOpen3.jpg"));

                    var isMatch = imgTurn.EqualTo(imgTemp);

                    imgTurn.Dispose();
                    imgTurn = null;
                    imgTemp.Dispose();
                    imgTemp = null;
                    if (isMatch)
                    {
                        CURRENT_RAISE = SECOND_RAISE;
                        return;
                    }
                }

                //open 4 card                        
                if (File.Exists(Path.Combine(IMAGE_PATH, IMG_OPEN4_NAME)))
                {
                    imgTurn = Image.FromFile(Path.Combine(IMAGE_PATH, IMG_OPEN4_NAME));
                    imgTemp = CaptureImage(this.HANDLER, 450, 250, 10, 10);
                    imgTemp.Save(Path.Combine(IMAGE_PATH, "IsOpen4.jpg"));
                    imgTemp.Dispose();
                    imgTemp = null;
                    imgTemp = Image.FromFile(Path.Combine(IMAGE_PATH, "IsOpen4.jpg"));

                    var isMatch = imgTurn.EqualTo(imgTemp);

                    imgTurn.Dispose();
                    imgTurn = null;
                    imgTemp.Dispose();
                    imgTemp = null;
                    if (isMatch)
                    {
                        CURRENT_RAISE = THIRD_RAISE;
                        return;
                    }
                }

                CURRENT_RAISE = FOURTH_RAISE;
            }
            catch { CURRENT_RAISE = 0; }
        }

        private int CurrentCallAmount()
        {
            int callAmount = 0;
            try
            {
                var imgTemp = CaptureImage(this.HANDLER, 380, 525, 115, 30);
                imgTemp.Save(Path.Combine(IMAGE_PATH, "CallAmount.jpg"));
                imgTemp.Dispose();
                imgTemp = null;

                string strAmount = string.Empty;
                strAmount = ExtractTextFromImage(Path.Combine(IMAGE_PATH, "CallAmount.jpg"));
                int counter = 1;
                while (string.IsNullOrEmpty(strAmount) && counter < 5)
                {
                    Thread.Sleep(100);
                    strAmount = ExtractTextFromImage(Path.Combine(IMAGE_PATH, "CallAmount.jpg"));
                    counter++;
                }

                int idxSymbol = strAmount.IndexOf("$");
                if (idxSymbol > 0)
                {
                    strAmount = strAmount.Substring(idxSymbol + 1, strAmount.Length - idxSymbol - 1);

                    string lastChar = string.Empty;
                    List<string> numberList = new List<string> { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };

                    while (strAmount.Length > 0 && !numberList.Contains(strAmount.Substring(strAmount.Length - 1, 1)))
                    {
                        lastChar = strAmount.Substring(strAmount.Length - 1, 1);
                        strAmount = strAmount.Substring(0, strAmount.Length - 1);
                    }

                    var values = strAmount.Split(".".ToCharArray());
                    switch (lastChar.ToUpper())
                    {
                        case "B": callAmount = Convert.ToInt32(values[0]) * 1000000000;
                            if (values.Length > 1) callAmount += Convert.ToInt32(values[1]) * 100000000;
                            break;

                        case "M": callAmount = Convert.ToInt32(values[0]) * 1000000;
                            if (values.Length > 1) callAmount += Convert.ToInt32(values[1]) * 100000;
                            break;

                        case "K": callAmount = Convert.ToInt32(values[0]) * 1000;
                            if (values.Length > 1) callAmount += Convert.ToInt32(values[1]) * 100;
                            break;

                        default:
                            callAmount = Convert.ToInt32(values[0]);
                            break;
                    }
                }
            }
            catch { callAmount = Int32.MaxValue; }

            return callAmount;
        }

        private bool IsHighCard_A()
        {
            var imgTemp = CaptureImage(this.HANDLER, 417, 406, 10, 10);
            imgTemp.Save(Path.Combine(IMAGE_PATH, IMAGE_TEMP_NAME1));
            imgTemp.Dispose();
            imgTemp = null;
            imgTemp = Image.FromFile(Path.Combine(IMAGE_PATH, IMAGE_TEMP_NAME1));

            string cardFileName = Path.Combine(IMAGE_PATH, "B_HA.jpg");
            if (File.Exists(cardFileName))
            {
                if (IsMatch(imgTemp, cardFileName))
                {
                    imgTemp.Dispose();
                    imgTemp = null;
                    return true;
                }
            }

            cardFileName = Path.Combine(IMAGE_PATH, "R_HA.jpg");
            if (File.Exists(cardFileName))
            {
                if (IsMatch(imgTemp, cardFileName))
                {
                    imgTemp.Dispose();
                    imgTemp = null;
                    return true;
                }
            }

            return false;
        }

        private bool IsHighCard_KQJ()
        {
            if (CURR_CARD < HIGH_CARD) return false;

            var imgTemp = CaptureImage(this.HANDLER, 440, 407, 10, 10);
            imgTemp.Save(Path.Combine(IMAGE_PATH, "SecondCard.jpg"));
            imgTemp.Dispose();
            imgTemp = null;
            imgTemp = Image.FromFile(Path.Combine(IMAGE_PATH, "SecondCard.jpg"));

            for (int i = HIGH_CARD; i < 15; i++)
            {
                string cardFileName = Path.Combine(IMAGE_PATH, string.Format("B_H{0}.jpg", i));
                if (File.Exists(cardFileName))
                {
                    if (IsMatch(imgTemp, cardFileName))
                    {
                        imgTemp.Dispose();
                        imgTemp = null;
                        return true;
                    }
                }

                cardFileName = Path.Combine(IMAGE_PATH, string.Format("R_H{0}.jpg", i));
                if (File.Exists(cardFileName))
                {
                    if (IsMatch(imgTemp, cardFileName))
                    {
                        imgTemp.Dispose();
                        imgTemp = null;
                        return true;
                    }
                }
            }

            return false;
        }

        private bool IsMatch(Image currentCard, string cardFileName)
        {
            var card = Image.FromFile(cardFileName);
            var isMatch = card.EqualTo(currentCard);

            card.Dispose();
            card = null;

            return isMatch;
        }

        private bool IsMatch(string orgFileName, string newName, int posX, int posY)
        {
            return IsMatch(orgFileName, newName, posX, posY, IMG_WIDTH, IMG_HEIGH);
        }

        private bool IsMatch(string orgFileName, string newName, int posX, int posY, int width, int heigh)
        {
            if (!File.Exists(Path.Combine(IMAGE_PATH, orgFileName))) return false;
            var orgImage = Image.FromFile(Path.Combine(IMAGE_PATH, orgFileName));

            var imgTemp = CaptureImage(this.HANDLER, posX, posY, width, heigh);
            imgTemp.Save(Path.Combine(IMAGE_PATH, newName));
            imgTemp.Dispose();
            imgTemp = null;
            imgTemp = Image.FromFile(Path.Combine(IMAGE_PATH, newName));

            var isMatch = orgImage.EqualTo(imgTemp);

            imgTemp.Dispose();
            imgTemp = null;
            orgImage.Dispose();
            orgImage = null;

            return isMatch;
        }

        #endregion

        #region "proccess images"

        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowDC(IntPtr hWnd);
        [DllImport("gdi32.dll")]
        public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjectSource, int nXSrc, int nYSrc, int dwRop);
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight);
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
        [DllImport("gdi32.dll")]
        public static extern bool DeleteDC(IntPtr hDC);
        [DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);
        [DllImport("gdi32.dll")]
        public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
        [DllImport("user32.dll")]
        public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
        public const int SRCCOPY = 13369376;

        private Image CaptureImage(IntPtr handle, int posX, int posY, int width, int height)
        {
            IntPtr hdcSrc = GetWindowDC(handle);

            IntPtr hdcDest = CreateCompatibleDC(hdcSrc);
            IntPtr hBitmap = CreateCompatibleBitmap(hdcSrc, width, height);

            IntPtr hOld = SelectObject(hdcDest, hBitmap);
            BitBlt(hdcDest, 0, 0, width, height, hdcSrc, posX, posY, SRCCOPY);
            SelectObject(hdcDest, hOld);
            DeleteDC(hdcDest);
            ReleaseDC(handle, hdcSrc);

            Image image = Image.FromHbitmap(hBitmap);
            DeleteObject(hBitmap);

            return image;
        }

        #endregion

        #region "extract text from OneNote"

        private string ExtractTextFromImage(string imagePath)
        {
            string result = string.Empty;
            try
            {
                RefreshOneNoteData(imagePath);
                result = ExtractText();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return result;
        }

        private string ExtractText()
        {
            string result = string.Empty;
            try
            {
                string strHierarchy;
                string strXML;

                OneNote.Application onApp = new OneNote.Application();

                // Get the hierarchy from the root to pages
                onApp.GetHierarchy(System.String.Empty, OneNote.HierarchyScope.hsPages, out strHierarchy);

                // Load the xml into a document
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(strHierarchy);

                //Create an XmlNamespaceManager for resolving namespaces.
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                nsmgr.AddNamespace("one", strNamespace);

                // Find the page ID of the active page
                var nodeList = xmlDoc.SelectNodes("//one:Page", nsmgr);

                XmlElement xmlActivePage = (XmlElement)xmlDoc.SelectSingleNode("//one:Page", nsmgr);

                //xmlActivePage = (XmlElement)nodeList[nodeList.Count - 1];

                string strActivePageID = xmlActivePage.GetAttribute("ID");
                string pageName = xmlActivePage.GetAttribute("name");

                // Get the content from the active page
                onApp.GetPageContent(strActivePageID, out strXML, OneNote.PageInfo.piBinaryData);
                xmlDoc.LoadXml(strXML);

                // Get the content from the active page
                onApp.GetPageContent(strActivePageID, out strXML, OneNote.PageInfo.piBinaryData);
                xmlDoc.LoadXml(strXML);

                //Get the data in the T nodes
                string strOcrContent = "";
                string strPageContent = "";
                XmlNodeList elemList = xmlDoc.GetElementsByTagName("one:OCRText");
                for (int i = 0; i < elemList.Count; i++)
                {
                    strOcrContent = elemList[i].InnerText; //Get the contents of the <![CDATA[]] block
                    strPageContent = strPageContent + strOcrContent;
                }

                result = strPageContent;
                onApp = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                //result = ex.Message;
            }
            finally
            {
                GC.Collect();
            }

            return result;
        }

        private bool RefreshOneNoteData(string strFilePath)
        {
            try
            {
                string strHierarchy;
                string strXML;
                OneNote.Application onApp = new OneNote.Application();
                
                // Get the hierarchy from the root to pages
                onApp.GetHierarchy(System.String.Empty, OneNote.HierarchyScope.hsPages, out strHierarchy);
                // Load the xml into a document
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(strHierarchy);

                //Create an XmlNamespaceManager for resolving namespaces.
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                nsmgr.AddNamespace("one", strNamespace);

                XmlElement xmlActivePage = (XmlElement)xmlDoc.SelectSingleNode("//one:Page", nsmgr);

                string strActivePageID = xmlActivePage.GetAttribute("ID");
                string pageName = xmlActivePage.GetAttribute("name");

                // Find the page ID of the active page
                var nodeList = xmlDoc.SelectNodes("//one:Page", nsmgr);
                                
                // Get the content from the active page
                onApp.GetPageContent(strActivePageID, out strXML, OneNote.PageInfo.piBinaryData);
                xmlDoc.LoadXml(strXML);
                nodeList = xmlDoc.SelectNodes("//one:Image", nsmgr);
                foreach (XmlNode node in nodeList)
                {
                    onApp.DeletePageContent(strActivePageID, node.Attributes["objectID"].Value);
                }
                InsertImageToCurrentPage(onApp, strActivePageID, pageName, strFilePath);
                
                onApp = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                GC.Collect();
            }

            return true;
        }

        private bool RemoveImageFromCurrentPage(OneNote.Application onenoteApp, string existingPageId, string pageToBeChange)
        {
            try
            {
                string m_xmlNewOutline = "<?xml version=\"1.0\"?><one:Page xmlns:one=\"{2}\" ID=\"{1}\"><one:Title><one:OE><one:T><![CDATA[{3}]]></one:T></one:OE></one:Title>{0}</one:Page>";

                string pageChangesXml = string.Format(m_xmlNewOutline, new object[] { "", existingPageId, strNamespace, pageToBeChange });
                onenoteApp.UpdatePageContent(pageChangesXml.ToString(), DateTime.MinValue);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                GC.Collect();
            }

            return true;
        }

        private bool InsertImageToCurrentPage(OneNote.Application onenoteApp, string existingPageId, string pageToBeChange, string imagePath)
        {
            try
            {
                string m_xmlImageContent = "<one:Image><one:Size width=\"{1}\" height=\"{2}\" isSetByUser=\"true\" /><one:Data>{0}</one:Data></one:Image>";
                string m_xmlNewOutline = "<?xml version=\"1.0\"?><one:Page xmlns:one=\"{2}\" ID=\"{1}\"><one:Title><one:OE><one:T><![CDATA[{3}]]></one:T></one:OE></one:Title>{0}</one:Page>";

                Bitmap bitmap = new Bitmap(imagePath);
                MemoryStream stream = new MemoryStream();
                bitmap.Save(stream, ImageFormat.Jpeg);
                string fileString = Convert.ToBase64String(stream.ToArray());

                string imageXmlStr = string.Format(m_xmlImageContent, fileString, bitmap.Width, bitmap.Height);
                string pageChangesXml = string.Format(m_xmlNewOutline, new object[] { imageXmlStr, existingPageId, strNamespace, pageToBeChange });
                onenoteApp.UpdatePageContent(pageChangesXml.ToString(), DateTime.MinValue);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                GC.Collect();
            }

            return true;
        }

        #endregion

        private void CaptureCard()
        {
            var i = 1;
            var cardTemp = Path.Combine(IMAGE_PATH, "CardsTemp", string.Format("temp{0}.jpg", i));
            //var carTemp1 = Path.Combine(IMAGE_PATH, "CardsTemp", string.Format("temp{0}_1.jpg", i));
            while (File.Exists(cardTemp))
            {
                i++;
                cardTemp = Path.Combine(IMAGE_PATH, "CardsTemp", string.Format("temp{0}.jpg", i));
                //carTemp1 = Path.Combine(IMAGE_PATH, "CardsTemp", string.Format("temp{0}_1.jpg", i));
            }

            var imgTemp = CaptureImage(this.HANDLER, 418, 407, 9, 13);
            imgTemp.Save(cardTemp);
            imgTemp.Dispose();
            imgTemp = null;

            //imgTemp = CaptureImage(this.HANDLER, 410, 400, 50, 50);
            //imgTemp.Save(carTemp1);
            //imgTemp.Dispose();
            //imgTemp = null;

            //click on fold button
            //autoit.ControlClick(this.Text, "", "[CLASS:MacromediaFlashPlayerActiveX; INSTANCE:1]", "LEFT", 1, 323, 573);
        }


    }
}
